# ommbot/partyline.py
#
#

""" provide partyline functionality """

__copyright__ = 'this file is in the public domain'
__credits__ = 'Aim'

import thread

class Partyline(object):

    """ this is the partyline """

    def __init__(self):
        self.socks = [] # partyline sockets list
        self.lock = thread.allocate_lock()

    def stop(self, bot):
        """ stop all user on bot """
        for i in self.socks:
            if i['bot'] == bot:
                try:
                    i['sock'].shutdown(2)
                    i['sock'].close()
                except:
                    pass

    def stop_all(self):
        """ stop every users on partyline """
        for i in self.socks:
            try:
                i['sock'].shutdown(2)
                i['sock'].close()
            except:
                pass

    def add_party(self, bot, sock, nick):
        ''' add a socket with nick to the list '''
        self.socks.append({'bot': bot, 'sock': sock, 'nick': nick})

    def del_party(self, nick):
        ''' remove a socket with nick from the list '''
        nick = nick.lower()
        self.lock.acquire()
        try:
            for socknr in range(len(self.socks)-1, -1, -1):	
                if self.socks[socknr]['nick'].lower() == nick:
                    del self.socks[socknr]
        finally:
            self.lock.release()

    def list_nicks(self):
        ''' list all connected nicks '''
        result = []
        for item in self.socks:
            result.append(item['nick'])
        return result

    def say_broadcast(self, txt):
        ''' broadcast a message to all ppl on partyline '''
        for item in self.socks:
            item['sock'].send("%s\n" % txt)

    def say_broadcast_notself(self, nick, txt):
        ''' broadcast a message to all ppl on partyline '''
        nick = nick.lower()
        for item in self.socks:
            if item['nick'] == nick:
                continue
            item['sock'].send("%s\n" % txt)

    def say_nick(self, nickfrom, nickto, msg):
        ''' say a message on the partyline to an user '''
        nickto = nickto.lower()
        for item in self.socks:
            if item['nick'].lower() == nickto:
                item['sock'].send("[%s -> %s] %s\n" % (nickfrom, nickto, msg))
                return

    def is_on(self, nick):
        ''' checks if user an is on the partyline '''
        nick = nick.lower()
        for item in self.socks:
            if item['nick'].lower() == nick:
                return 1
        return 0
